package com.demo.function.hutool;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.google.common.collect.Lists;
import lombok.Data;

import java.util.List;

/**
 * 树形数据结构服务
 */
public class TreeService {

    /**
     * 生成树形结果集合
     * @return 树形结构集合
     */
    public List<Tree<Integer>> genTree() {
        List<FinanceSubject> subjects = initFinanceSubjects();

        TreeNodeConfig config = new TreeNodeConfig();
        config.setIdKey("id").setParentIdKey("pid").setChildrenKey("details");

        return TreeUtil.build(subjects, 0, config, (node, tree) -> {
            tree.setId(node.getId()).setParentId(node.getPid()).setName(node.getName());

            // 额外的值
            tree.put("level", node.getLevel());
        });
    }

    /**
     * 初始化数据
     * @return 对象集合
     */
    private List<FinanceSubject> initFinanceSubjects() {
        List<FinanceSubject> subjects = Lists.newArrayList();
        for (int i = 1; i < 5; i++) {
            FinanceSubject subject1 = new FinanceSubject();

            int id1 = i + 100;
            subject1.setId(id1);
            if (i == 1) {
                subject1.setPid(0);
            } else {
                subject1.setPid(id1 - 1);
            }
            subject1.setLevel(i);
            subject1.setName("name" + Math.random());

            int id2 = i + 200;
            FinanceSubject subject2 = new FinanceSubject();
            subject2.setId(id2);
            if (i == 1) {
                subject2.setPid(0);
            } else {
                subject2.setPid(id2 - 1);
            }
            subject2.setLevel(i);
            subject2.setName("name" + Math.random());

            subjects.add(subject1);
            subjects.add(subject2);
        }
        return subjects;
    }

    @Data
    public static class FinanceSubject {
        private int id;
        private int pid;
        private String name;
        private int level;
    }
}
